<?php

namespace app\order\logic;

use app\common\library\Excel;
use app\data\util\HttpUtil;
use think\facade\Db;

class OrderSplitLogic extends BasicLogic
{


    /**
     * @desc     待拆分订单列表接口
     * @date     2025-04-03
     * @author   luckyXiong
     */
    public function getList($params=[]){
        $limit           = $params['limit'] ?? 10;
        $order_number    = $params['order_number'] ?? "";
        $order_id        = $params['order_id'] ?? 0;
        $shop_id         = $params['shop_id'] ?? "";
        $split_status    = $params['split_status'] ?? "";
        $send_status     = $params['send_status'] ?? "";
        $sku             = $params['sku'] ?? "";
        $create_time     = $params['create_time'] ?? "";
        $where           = [];

        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if ($order_id) {
            $order_ids_raw = trim($params['order_id']);
            $order_ids_filtered = array_filter(explode("\n", $order_ids_raw), 'trim');
            if (!empty($order_ids_filtered)) {
                $where[] = ['order_id', 'in', $order_ids_filtered];
            }
        }

        if ($order_number) {
            $order_numbers_raw = trim($params['order_number']);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            if (!empty($order_numbers_filtered)) {
                $where[] = ['order_number', 'in', $order_numbers_filtered];
            }
        }

        if ($shop_id) {
            $where[] = ['shop_id', '=', $shop_id];
        }

        if ($send_status) {
            $where[] = ['send_status', '=', $send_status];
        }


        if ($sku) {
            $where[] = ['sku', 'like', '%' . $sku . '%'];
        }

        if ($split_status) {
            $where[] = ['split_status', '=', $split_status];
        }


        $res = Db::name('order_explode')
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $list = $res->items();
        $shop_ids       = array_column($list,'shop_id');
        $shop_names     = Db::name('shops')->field('id,name,domain')->whereIn('id',$shop_ids)->select()->toArray();
        $shop_names_map = array_column($shop_names,null,'id');
        foreach($list as $k=>$v){
            $shopNames             = $shop_names_map[$v['shop_id']]??[];
            $shop_name             = $shopNames['name']??'';
            $list[$k]['shop_name'] = $shop_name;
            if($v['split_res']){
                $message = json_decode($v['split_res'],true);
                $message = $message['data']['fulfillmentOrderSplit']['userErrors'][0]['message']??'';
                $list[$k]['split_res'] = $message;
            }
        }

        $data = [
            'list'  => $list,
            'total' => $res->total(),
        ];
        return $data;
    }


    /**
     * @desc     待拆分订单列表详情接口
     * @date     2025-04-03
     * @author   luckyXiong
     */
    public function getExplodeDetail($params=[]){
        $limit    = $params['limit'] ?? 10;
        $order_id = $params['order_id']??'';
        $field    = 'id,order_id,order_number,shop_id,track_number,sku,num,hwc_warehouse,create_time';
        $res = Db::name('order_explode_detail')
            ->field($field)
            ->where('order_id',$order_id)
            ->order('id desc')
            ->paginate($limit);
        $list = $res->items();
        $shop_ids       = array_column($list,'shop_id');
        $shop_names     = Db::name('shops')->field('id,name,domain')->whereIn('id',$shop_ids)->select()->toArray();
        $shop_names_map = array_column($shop_names,null,'id');
        //批量获取产品图片地址;
        $sku_info        = array_column($list,'sku');
        $sku_image_info  = Db::name('product_seller_sku')->field('id,seller_sku,image_info')->whereIn('seller_sku',$sku_info)->select()->toArray();
        $image_infos_map = array_column($sku_image_info,'image_info','seller_sku');

        if(!$list) {
            return  [
                'list'  => [],
                'total' => 0,

            ];
        }

        foreach($list as $k=>$v){
            $shopNames             = $shop_names_map[$v['shop_id']]??[];
            $shop_name             = $shopNames['name']??'';
            $list[$k]['shop_name'] = $shop_name;

            $imange_url = $image_infos_map[$v['sku']]??'';

            if(!$imange_url){
                $imange_url = Config('Logisticskey.product_image_default');
            }
            $list[$k]['imange_url'] = $imange_url;
        }

        $data = [
            'list'  => $list,
            'total' => $res->total(),
        ];
        return $data;
    }


    /**
     * @desc     拆单接口
     * @date     2025-04-07
     * @author   luckyXiong
     */
    public function splitOrder($params){
        htmlLog(['params'=>$params],OPERATE_LOG . date('Ym') . '/splitOrder_param/' . date('Ymd') . '.txt');
        $orderId        = $params['order_id']??'';
        $shop_id        = $params['shop_id'] ?? '';
        $shop_info      = Db::name('shops')->where('id', $shop_id)->find();
        $token          = $shop_info['app_secret'];
        $version        = Config('Logisticskey.shopify.new_api_versoin');
        $operation      = Config('Logisticskey.shopify.graphql_path');
        //获取订单的物流详情;
        $url                  = $shop_info['myshopify_domain'] .Config('Logisticskey.shopify.create_fullment_id').$orderId."/fulfillment_orders.json";
        $fulfillment_orders   = HttpUtil::getUrl($url, $shop_info);
        $split_url            = $shop_info['myshopify_domain'].$version.$operation;
        if(!isset($fulfillment_orders['fulfillment_orders'][0]['id']) || empty($fulfillment_orders['fulfillment_orders'][0]['id']))  return  '暂无fullment_id';
        //物流id
        $fulfillment_order_id = $fulfillment_orders['fulfillment_orders'][0]['id'];
        //获取当前订单的详细信息;
        $info      = Db::name('order_info')
            ->field('id,shop_id,order_id,info_id,sku,quantity as num')
            ->where(['order_id'=>$orderId])
            ->where('sku','<>','')
            ->where('is_seel','<>',1)
            ->select()
            ->toArray();

        $split_arr = $fulfillmentOrderLineItems = [];

        foreach($info as  $k=>$v){
            $v['sku'] = self::get_sample_sku($v['sku']);
            $new_quantity = Db::name('inventory_hwc')
                ->where('inventory_quantity','>=',$v['num'])
                ->where('sku',$v['sku'])
                ->value('inventory_quantity');
            if($new_quantity){
                //组装待拆分新数组的数据;
                $split_arr[$k]['info_id'] = $v['info_id'];
                $split_arr[$k]['num']     = $v['num'];
            }
        }

        $line_items = $fulfillment_orders['fulfillment_orders'][0]['line_items']??[];
        if($line_items && $split_arr){
            $line_items_map = array_column($line_items,'id','line_item_id');
            foreach($split_arr as $v){
                $line_id           = $line_items_map[$v['info_id']]??'';
                $temp['id']        = 'gid://shopify/FulfillmentOrderLineItem/'.$line_id;
                $temp['quantity']  = $v['num'];
                $fulfillmentOrderLineItems[] = $temp;

            }
        }
        $fulfillmentOrderSplits = [
            [
                'fulfillmentOrderId'        => "gid://shopify/FulfillmentOrder/".$fulfillment_order_id,
                'fulfillmentOrderLineItems' => $fulfillmentOrderLineItems
            ]
        ];
        // 构建 GraphQL mutation
        $mutation = <<<QUERY
    mutation fulfillmentOrderSplit(\$fulfillmentOrderSplits: [FulfillmentOrderSplitInput!]!) {
        fulfillmentOrderSplit(fulfillmentOrderSplits: \$fulfillmentOrderSplits) {
            fulfillmentOrderSplits {
                fulfillmentOrder {
                    id
                    lineItems(first: 10) {
                        edges {
                            cursor
                            node {
                                id
                                totalQuantity
                            }
                        }
                    }
                }
                remainingFulfillmentOrder {
                    id
                    lineItems(first: 10) {
                        edges {
                            cursor
                            node {
                                id
                                totalQuantity
                            }
                        }
                    }
                }
            }
            userErrors {
                field
                message
            }
        }
    }
QUERY;

        $payload  = [
            'query'     => $mutation,
            'variables' => [
                'fulfillmentOrderSplits' => $fulfillmentOrderSplits
            ]
        ];
        $result = HttpUtil::postUrlShopify($split_url,$payload,$token);
        $fulfillmentOrders = $result['data']['fulfillmentOrderSplit']['fulfillmentOrderSplits']??[];
        htmlLog(['params'=>$payload,'response'=>$result],OPERATE_LOG . date('Ym') . '/splitOrder/' . date('Ymd') . '.txt');
        if(empty($fulfillmentOrders)){
            //2025-04-11 拆单失败记录失败原因;
            Db::name('order_explode')->where(['order_id'=>$orderId])->update(
                [
                    'split_status'=>2,
                    'split_res'   =>json_encode($result),
                ]
            );
            return  true;
        }else{
            //2025-04-11 拆单成功
            Db::name('order_explode')->where(['order_id'=>$orderId])->update(
                [
                    'split_status'=>1,
                    'split_res'   =>json_encode($result),
                ]
            );
            self::add_explode_info($shop_info,$orderId,$fulfillmentOrders);
        }
        return   true;
    }


    /**
     * @desc   批量更新海外仓库存
     * @author luckyXiong
     * @date   2025-04-08
     */
    public function update_hwc(){
        $url               =Config('Logisticskey.999_url').'/api/check/update_hwc_inventory';
        $info              = [
            'ids'       =>1,
        ];
        $res               = HttpUtil::postDataCurl($url, $info);
    }


    /**
     * @desc   标记已处理
     * @author luckyXiong
     * @date   2025-04-14
     */
    public function update_change($params){
        $ids  = $params['ids']??'';
        Db::name('order_explode')->whereIn('id', $ids)->update(
            [
                'send_status'   => 2,
            ]
        );
    }



    /**
     * @desc   导出处理
     * @author luckyXiong
     * @date   2025-04-14
     */
    public function export_info($params=[]){
        $order_id  = $params['order_id']??'';
        Db::name('order_explode')->where('order_id', $order_id)->update(
            [
                'send_status'   => 2,
            ]
        );

        //导出需要拆单的数据;
        $field    = 'id,order_id,order_number,shop_id,sku,num,hwc_warehouse,create_time';
        $list     = Db::name('order_explode_detail')
            ->field($field)
            ->where('order_id',$order_id)
            ->order('id desc')
            ->select()
            ->toArray();

        $shop_ids       = array_column($list,'shop_id');
        $shop_names     = Db::name('shops')->field('id,name,domain')->whereIn('id',$shop_ids)->select()->toArray();
        $shop_names_map = array_column($shop_names,null,'id');

        foreach($list as $k=>$v){
            $shopNames             = $shop_names_map[$v['shop_id']]??[];
            $shop_name             = $shopNames['name']??'';
            $list[$k]['shop_name'] = $shop_name;
            $list[$k]['hwc_warehouse'] = $v['hwc_warehouse'] > 0 ? '海外仓' : '江夏仓';
        }


        $header[] = ['店铺', 'shop_name'];
        $header[] = ['订单编号', 'order_number'];
        $header[] = ['SKU', 'sku'];
        $header[] = ['sku数量', 'num'];
        $header[] = ['仓库', 'hwc_warehouse'];
        $header[] = ['创建时间', 'create_time'];
        $fileName = "export_order_split_" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }


    /**
     * @desc   导出主页数据处理
     * @author luckyXiong
     * @date   2025-04-14
     */
    public function export_explode_info($params=[]){
        $order_number    = $params['order_number'] ?? "";
        $order_id        = $params['order_id'] ?? 0;
        $shop_id         = $params['shop_id'] ?? "";
        $split_status    = $params['split_status'] ?? "";
        $send_status     = $params['send_status'] ?? "";
        $sku             = $params['sku'] ?? "";
        $create_time     = $params['create_time'] ?? "";
        $where           = [];


        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        if ($order_id) {
            $order_ids_raw = trim($params['order_id']);
            $order_ids_filtered = array_filter(explode("\n", $order_ids_raw), 'trim');
            if (!empty($order_ids_filtered)) {
                $where[] = ['order_id', 'in', $order_ids_filtered];
            }
        }

        if ($order_number) {
            $order_numbers_raw = trim($params['order_number']);
            $order_numbers_filtered = array_filter(explode("\n", $order_numbers_raw), 'trim');
            if (!empty($order_numbers_filtered)) {
                $where[] = ['order_number', 'in', $order_numbers_filtered];
            }
        }

        if ($shop_id) {
            $where[] = ['shop_id', '=', $shop_id];
        }


        if($send_status){
            $where[] = ['send_status', '=', $send_status];
        }

        if ($sku) {
            $where[] = ['sku', 'like', '%' . $sku . '%'];
        }

        if ($split_status) {
            $where[] = ['split_status', '=', $split_status];
        }


        $field = 'id,order_id,order_number,shop_id,sku,num,send_status,create_time';
        $list = Db::name('order_explode')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->select()
            ->toArray();


        $shop_ids       = array_column($list,'shop_id');
        $shop_names     = Db::name('shops')->field('id,name,domain')->whereIn('id',$shop_ids)->select()->toArray();
        $shop_names_map = array_column($shop_names,null,'id');

        foreach($list as $k=>$v){
            $shopNames             = $shop_names_map[$v['shop_id']]??[];
            $shop_name             = $shopNames['name']??'';
            $list[$k]['shop_name'] = $shop_name;
        }

        $header[] = ['店铺', 'shop_name'];
        $header[] = ['订单编号', 'order_number'];
        $header[] = ['SKU', 'sku'];
        $header[] = ['sku数量', 'num'];
        $header[] = ['创建时间', 'create_time'];
        $fileName = "export_order_explode_" . time();
        return Excel::exportData($list, $header, $fileName, 'xlsx');
    }


    /**
     * @desc   拆分订单数据存储
     * @author luckyXiong
     * @date   2025-04-10
     */
    public function add_explode_info($shop_info,$orderId,$fulfillmentOrders){
        $url                  = $shop_info['myshopify_domain'] .Config('Logisticskey.shopify.create_fullment_id').$orderId."/fulfillment_orders.json";
        $fulfillment_orders   = HttpUtil::getUrl($url, $shop_info);
        $remainingFulfillmentOrder =  $fulfillmentOrders[0]['remainingFulfillmentOrder']['id']??'';
        $parts                = explode('/', $remainingFulfillmentOrder); // 将字符串按照 '/' 分割
        $remainingId          = end($parts); // 取最后一个部分
        $fulfillments         = $fulfillment_orders['fulfillment_orders']??[];
        $explode_list         =  [];
        $shop_numbers         = Config('Logisticskey.shop_number');
        $number               = $shop_numbers[$shop_info['id']]??'7256335';
        $order_name           = Db::name('order')->where(['order_id'=>$orderId])->value('order_number');
        $order_number         = $number.'-'.$order_name;
        //获取数据整合;
        foreach($fulfillments as $v){
                $sku_item                    = self::get_explode_sku($v['line_items']);
                if(!$sku_item){
                    continue;
                }
                $temp['sku']                 = $sku_item;
                $count_num                   = self::get_explode_sku_num($v['line_items']);
                $temp['order_id']            = $orderId;
                $temp['order_number']        = $order_number;
                $temp['shop_id']             = $shop_info['id'];
                $temp['fulfillment_order_id']= $v['id'];
                $temp['line_items']          = json_encode($v['line_items']);
                $temp['destination']         = json_encode($v['destination']);
                $temp['num']                 = $count_num;
                $temp['track_number']        = '';
                $temp['create_time']         = date("Y-m-d H:i:s");
                $temp['hwc_warehouse']       = 0;
                //获取海外仓发货部分;
                if($v['id'] == $remainingId){
                       $temp['hwc_warehouse'] = 1;
                       self::add_hwc_info($v,$order_number,$shop_info['id']);
                }
                $explode_list[]              = $temp;
         }
         //存储拆分详情数据;
         $exist_info = Db::name('order_explode_detail')->where(['order_id'=>$orderId])->select()->toArray();
         if(!$exist_info && $explode_list){
             Db::name('order_explode_detail')->insertAll($explode_list);
         }
         return  true;
    }


    /**
     * @desc   拆分订单数据补发
     * @author luckyXiong
     * @date   2025-08-10
     */
    public function add_explode_detail($params=[]){
        $order_id             = $params['order_id']??'';
        $shop_id              = $params['shop_id']??'';
        $remainingId          = $params['remainingId']??'';
        $shop_info            = Db::name('shops')->where(['id'=>$shop_id])->find();
        $url                  = $shop_info['myshopify_domain'] .Config('Logisticskey.shopify.create_fullment_id').$order_id."/fulfillment_orders.json";
        $fulfillment_orders   = HttpUtil::getUrl($url, $shop_info);
        $fulfillments         = $fulfillment_orders['fulfillment_orders']??[];
        $explode_list         = [];
        $shop_numbers         = Config('Logisticskey.shop_number');
        $number               = $shop_numbers[$shop_info['id']]??'7256335';
        $order_name           = Db::name('order')->where(['order_id'=>$order_id])->value('order_number');
        $order_number         = $number.'-'.$order_name;
        //获取数据整合;
        foreach($fulfillments as $v){
            $sku_item                    = self::get_explode_sku($v['line_items']);
            if(!$sku_item){
                continue;
            }
            $temp['sku']                 = $sku_item;
            $count_num                   = self::get_explode_sku_num($v['line_items']);
            $temp['order_id']            = $order_id;
            $temp['order_number']        = $order_number;
            $temp['shop_id']             = $shop_info['id'];
            $temp['fulfillment_order_id']= $v['id'];
            $temp['line_items']          = json_encode($v['line_items']);
            $temp['destination']         = json_encode($v['destination']);
            $temp['num']                 = $count_num;
            $temp['track_number']        = '';
            $temp['create_time']         = date("Y-m-d H:i:s");
            $temp['hwc_warehouse']       = 0;
            //获取海外仓发货部分;
            if($v['id'] == $remainingId){
                $temp['hwc_warehouse'] = 1;
                self::add_hwc_info($v,$order_number,$shop_info['id']);
            }
            $explode_list[]              = $temp;
        }
        //存储拆分详情数据;
        $exist_info = Db::name('order_explode_detail')->where(['order_id'=>$order_id])->select()->toArray();
        if(!$exist_info && $explode_list){
            Db::name('order_explode_detail')->insertAll($explode_list);
        }
        return  true;
    }


    /**
     * @desc   sku处理
     * @author luckyXiong
     * @date   2025-04-09
     */
    private function get_explode_sku($lines){
            $info_ids = array_column($lines,'line_item_id');
            $sku_info = Db::name('order_info')
                ->field('id,sku,quantity as num')
                ->whereIn('info_id',$info_ids)
                ->where('sku','<>','')
                ->where('is_seel','<>',1)
                ->select()
                ->toArray();
            $skus = [];
            foreach($sku_info as $v){
                 $skus[]  = self::get_seller_sku($v['sku'],$v['num']);
          }
          return implode(',',$skus);
    }


    /**
     * @desc   获取sku件数
     * @author luckyXiong
     * @date   2025-04-09
     */
    private function get_explode_sku_num($lines){
        $info_ids = array_column($lines,'line_item_id');
        $sku_info = Db::name('order_info')
            ->field('id,sku,quantity as num')
            ->whereIn('info_id',$info_ids)
            ->where('sku','<>','')
            ->where('is_seel','<>',1)
            ->select()
            ->toArray();
        $num = array_sum(array_column($sku_info,'num'));
        return $num ?:0;
    }


    /**
     * @desc   存储海外仓信息
     * @author luckyXiong
     * @date   2025-04-10
     */
    private function add_hwc_info($info,$order_number,$shop_id){
            $shop_names = Config('Logisticskey.shop_names');
            $first_name = $info['destination']['first_name']??'';
            $last_name  = $info['destination']['last_name']??'';
            //update  2025-08-01  地址修复;
            $address1   = $info['destination']['address1']??'';
            $address2   = $info['destination']['address2']??'';
            $address    = $address1;
            if($address2){
              $address = $address1.' '.$address2;
            }
            $insert_info = [
                   'order_id'           => $info['order_id'],
                   'honey_order_number' => $order_number,
                   'sku'                => self::get_explode_sku($info['line_items']),
                   'num'                => count($info['line_items']),
                   'shop_id'            => $shop_id,
                   'shop_name'          => $shop_names[$shop_id]??'',
                   'buyer_name'         => $first_name.' '.$last_name,
                   'buyer_email'        => $info['destination']['email']??'',
                   'address'            => $address,
                   'city'               => $info['destination']['city']??'',
                   'state'              => $info['destination']['province']??'',
                   'post_code'          => $info['destination']['zip']??'',
                   'phone'              => $info['destination']['phone']??'0000000000',
                   'country'            => $info['destination']['country']??'',
                   'split_status'       => 1,
                   'warehouse_id'       => 3,
                   'ship_status'        => 8,
                   'fullment_order_id'  => $info['id']??'',
                   'create_time'        => date("Y-m-d H:i:s"),
                   'update_time'        => date("Y-m-d H:i:s"),
                   'warehouse_id_plan'  => 3,
            ];
            $exist_info = Db::name('order_shopify_list')->where(['order_id'=>$info['order_id']])->find();
            if(!$exist_info){
                Db::name('order_shopify_list')->insert($insert_info);
            }
            return  true;
    }



    /**
     * @desc   尾部处理
     * @author luckyXiong
     * @date   2025-04-09
     */
    public function get_sample_sku($skus=''){
        $pattern = '/\+/';
        if (!preg_match($pattern, $skus)) { // 仅处理不含加号的条目
            $pos = strpos($skus, '/');
            if ($pos !== false) {
                $sku = substr($skus, 0, $pos);
            }else{
                $sku = $skus;
            }
        }else{
            $sku = $skus;
        }
        return  $sku;
    }



    /**
     * @desc  数据清洗生产
     * @author xx
     * @date 2024-07-10
     */
    public function get_seller_sku($sku,$num=1){
        return get_shopify_spu($sku,$num);
    }


}